import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

public class CollectionsThreadSafe {

    public static void main(String[] args) {
//        listNotSafe();
        mapNotSafe();
    }


//    ConcurrentModificationException
//    public static void listNotSafe() {
//        List<String> list = new ArrayList<>();
//        for (int i = 0; i < 100; i++) {
//            new Thread(() -> {
//                list.add(UUID.randomUUID().toString().substring(0, 1));
//                System.out.println(list);
//            }, "a").start();
//        }
//    }

    public static void listNotSafe() {
        List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 1));
                System.out.println(Thread.currentThread().getName() + list);
            }, String.valueOf(i) + ":  ").start();
        }
    }

    public static void mapNotSafe() {
        Map<String, String> map = new ConcurrentHashMap<>();

        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                map.put(String.valueOf(i), UUID.randomUUID().toString().substring(0, 1));
                System.out.println(map);
            }
        }, "a").start();
    }
}
